<?php
/* SVN FILE: $Id: submissions_controller.php 34 2009-10-17 13:42:12Z kenreily@gmail.com $ */
/**
 * Short description for file.
 *
 * Long description for file
 *
 * PHP versions 4 and 5
 *
 * Recenseo: Online submission and reviewing for education
 * Copyright 2008-2009, Ken Reily
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * $Date: 2009-10-17 13:42:12 +0000 (Sat, 17 Oct 2009) $
 * $Revision: 34 $
 * $Author: kenreily@gmail.com $
 * $HeadURL: http://recenseo.googlecode.com/svn/trunk/app/controllers/submissions_controller.php $
 */
class SubmissionsController extends AppController
{
  var $name = 'Submissions';
  var $helpers = array('Time');
  var $components = array('Email');
  var $uses = array('Submission','AssignedAssessment');
  
  function add($assignment_id = null)
  {
    $user_id = $this->Session->read('Auth.User.id');

    $assignment_info = $this->Submission->Assignment->getForId($assignment_id);
    $this->set('assignment_info',$assignment_info);
    $this->set('assignment_id',$assignment_id);

   $grading_options = $this->Submission->GradingOption->getListForAssignment($assignment_id);
    $this->set('gradingOptions',$grading_options);

    // Calculate remaining flex days based on previous submissions
    $flex_day_allowance = $this->Submission->User->flexDayAllowance(
      $user_id,
      $assignment_info[0]['c']['id']);
    
    $flex_day_usage = $this->Submission->User->flexDayUsage(
      $user_id,
      $assignment_info[0]['c']['id']);
      
    $flex_days_remaining = $flex_day_allowance[0]['cu']['flex_day_allowance'];
    
    foreach ($flex_day_usage as $flex_days_used)
    {
      $flex_days_remaining -= $flex_days_used[0]['flex_days_used'];
    }
    
    $this->set('flex_days_remaining',$flex_days_remaining);

    // Calculate required flex days for this submission
    $flex_days_required = ceil((time() - strtotime($assignment_info[0]['a']['due'])) / 86400);

    if ($flex_days_required < 1)
    {
      $flex_days_required = 0;
    }
    
    $this->set('flex_days_required',$flex_days_required);
    
    // Calculate the deduction for this submission.
    // Deduction = 10% per day not covered with flex days.
    $deduction = 0;
    
    $diff = $flex_days_required - $flex_days_remaining;
    
    if ($diff > 0)
    {
      $deduction = 10 * $diff;
    }
    
    $this->set('deduction',$deduction);
    
    if (count($assignment_info) > 0)
    {
      $this->pageTitle = "Submit {$assignment_info[0]['a']['name']}";

      if (!empty($this->data)) 
      {
        if (time() < strtotime($assignment_info[0]['a']['cutoff']))
        {
          if (is_uploaded_file($this->data['Submission']['File']['tmp_name'])) 
          {
            $this->data['Submission']['user_id'] = $user_id;
            $this->data['Submission']['assignment_id'] = $assignment_id;
            $this->data['Submission']['active'] = 1;
            
            if ($deduction > 0)
            {
              $this->data['Submission']['late_deduction_pct'] = $deduction;
            }
          
            $file = fopen($this->data['Submission']['File']['tmp_name'], "r");
            $fileData = fread($file,$this->data['Submission']['File']['size']);

            $this->data['Submission']['file_name'] = $this->data['Submission']['File']['name'];
            $this->data['Submission']['file_type'] = $this->data['Submission']['File']['type'];
            $this->data['Submission']['file_size'] = $this->data['Submission']['File']['size'];
            $this->data['Submission']['file_data'] = $fileData;

            if ($this->Submission->save($this->data)) 
            {
              $this->set('submission_id',$this->Submission->id);

              // TODO: Move email address to user table.
              $this->Email->to = $this->Session->read('Auth.User.email');
              $this->Email->subject = 'Submission Confirmation';
              $this->Email->from = 'Ken Reily <reil0037@umn.edu>';
              $this->Email->bcc = array('Ken Reily <reil0037@umn.edu>');
              $this->Email->template = 'confirm_submission';
              $this->Email->sendAs = 'text';
              $this->Email->send();         
             
              $this->flash('Submission successful.','/submissions/view/' . $this->Submission->id);
            }
          }        
        }
        else
        {
          $this->flash('Cutoff time has passed. You can no longer submit this assignment.',"/assignments/index/{$assignment_info[0]['c']['id']}");
        }
      }
    }
  }
  
  function download($id)
  {
    Configure::write('debug', 0);
    $file = $this->Submission->getForDownload($id,$this->Session->read('Auth.User.id'));

    header('Content-type: ' . $file[0]['s']['file_type']);
    header('Content-length: ' . $file[0]['s']['file_size']);
    header('Content-Disposition: attachment; filename="'.$file[0]['s']['file_name'].'"');
    echo $file[0]['s']['file_data'];

    exit();
  }

  function admin_index($assignment_id)
  {
    $submissions = $this->Submission->getForAdminIndex($assignment_id);
    $this->set('submissions',$submissions);
  }
  
  function resubmit($id)
  {
    $submission_info = $this->Submission->getForId($id,$this->Session->read('Auth.User.id'));

    if (!empty($submission_info) && time() < strtotime($submission_info['Assignment']['due']))
    {
      $this->Submission->id = $id;
      $this->Submission->saveField('active',0);
      $this->flash('Submission taken back successfully.','/submissions/add/' . $submission_info['Assignment']['id']);
    }
    else
    {
      $this->flash('Due date/time has passed. You may no longer take back this assignment.',"/submissions/view/{$id}");
    }
  }

 
  function view($id)
  {
    $user = $this->Session->read('Auth.User');
    // Get submission info.
    $conds = array('Submission.id' => $id);

    $submission = $this->Submission->find('first',
      array('conditions' => $conds,
        'fields' => array('Submission.id',
			  'Submission.user_id',
          'Submission.file_name',
          'Submission.file_type',
          'Submission.file_size',
          'Submission.comments',
          'Submission.late_deduction_pct',
	  'Submission.active',
          'Submission.created',
          'Assignment.id',
          'Assignment.name',
          'Assignment.course_id',
          'Assignment.due',
          'Assignment.assessments_due',
          'GradingOption.name'),
        'recursive' => 0));
    $this->set('submission',$submission);

    if (empty($submission)) 
    {
      $this->Session->setFlash('Submission not found.');
    }
    else if ($submission['Submission']['user_id'] != $user['id'] &&
	     $user['role'] != 'Instructor')
    {
      $this->Session->setFlash('You are not authorized to view this submission.');
      $this->set('submission',null);
    }
    else if ($submission['Submission']['active'] != 1)
    {
      $this->Session->setFlash('This submission is obsolete.');
      $this->set('submission',null);
    }
    else
    {
      $this->pageTitle = "Submission #{$id}";

      // Get course info
      $conds = array('id' => $submission['Assignment']['course_id']);
      $this->set('course',
		 $this->Submission->Assignment->Course->find('first',
							     array('conditions' => $conds, 'recursive' => -1)));
      
      // Get assessments of this submission.
      $conds = array('Submission.id' => $submission['Submission']['id'],
		     'NOT' => array('Assessment.submitted' => ''));
      $assessments = $this->Submission->Assessment->find('all',
							 array('conditions' => $conds,
							       'fields' => array('Assessment.id',
										 'Assessment.submitted',
										 'Assessment.score',
										 'Assessment.author_rating'),
							       'order' => 'Assessment.submitted'));
      $this->set('assessments',$assessments);
    
      // Get assessments for this user for this assignment.
      $user_asmts = $this->Submission->Assessment->
	countForUserAssignment($user['id'], $submission['Assignment']['id']);
      $this->set('user_asmts',$user_asmts);
    }    
  }
}
?>